package com.qicheng.wlhyspider.guizhou.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qicheng.wlhyspider.common.HttpUtils;
import com.qicheng.wlhyspider.common.RedisUtils;
import com.qicheng.wlhyspider.guizhou.common.GzPageResult;
import com.qicheng.wlhyspider.guizhou.entity.GzVehicleEntity;
import com.qicheng.wlhyspider.guizhou.mapper.GzVehicleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/guizhou/vehicle")
@Slf4j
public class GzVehicleController {
    private final GzVehicleMapper gzVehicleMapper;
    private final RedisUtils redisUtils;


    public GzVehicleController(GzVehicleMapper gzVehicleMapper, RedisUtils redisUtils) {
        this.gzVehicleMapper = gzVehicleMapper;
        this.redisUtils = redisUtils;
    }

    private List<Integer> tjDriverIdList = new ArrayList<>();

    @GetMapping("/save")
    public String save(@RequestParam("page") Integer page, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        Long maxPage = 662L;
        if (CollectionUtil.isEmpty(tjDriverIdList)){
            tjDriverIdList =  gzVehicleMapper.selectList(Wrappers.<GzVehicleEntity>lambdaQuery()
                    .select(GzVehicleEntity::getId)).stream().map(GzVehicleEntity::getId).collect(Collectors.toList());
        }



//        Integer limit = 500;
        Integer pages = 10;
//        LoginUtils.login();
        CompletableFuture<Object>[] futures = new CompletableFuture[pages];
        for (int i = 0; i < pages; i++) {
            int finalPage = page + i;
            CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
                try {
                    saveAll(finalPage,  startDate, endDate);
                    log.info("车辆插入，第{}页成功", finalPage);
                } catch (Exception e) {
                    log.error("车辆插入，第{}页失败", finalPage);
                    log.error(e.getMessage(), e);
                    e.printStackTrace();
                }
                return null;
            });
            futures[i] = future;
        }
        // todo 最好在循环插入的时候也捕获异常
        log.info("====futures.length=={}",futures.length);
        CompletableFuture<Void> cf = CompletableFuture.allOf(futures);

        // 如果执行成功:
        cf.thenAccept((result) -> {
            log.info("车辆插入成功！！！");
            if (page < maxPage){
                save(page + pages,startDate,endDate);
            }

        });
        // 如果执行异常:
        cf.exceptionally((e) -> {
            e.printStackTrace();
            log.info("车辆插入失败！！！");
            return null;
        });
        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }



        return "车辆插入成功！！！";

    }

    private String saveAll(Integer page, String startDate, String endDate) {
        Integer limit = 1000;
        String url = "https://wlhy.org.cn/wlhy-ck-query/vehicleMessage/getList";
        JSONObject requestBody = new JSONObject();
        requestBody.put("pageNumber",page);
        requestBody.put("pageSize",limit);
        HttpResponse httpResponse = HttpUtils.GzHttpPost(url,redisUtils,requestBody);
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            GzPageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), GzPageResult.class);
            GzPageResult.Data data = pageResult.getData();
            List<GzVehicleEntity> list = JSONArray.parseArray(JSONArray.toJSONString(data.getList()), GzVehicleEntity.class);
            list = list.stream().filter(i -> !tjDriverIdList.contains(i.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(list)){
                gzVehicleMapper.insertBatchSomeColumn(list);
            }
            log.info(String.format("车辆查询，%s到%s，第%s页，总页数%s",startDate,endDate,page,data.getCount() / limit));
//            if (page < result.getPages()) {
//                page++;
//                return save(page, startDate, endDate);
//            }

        }  else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
//            return "返回：登录信息失效";
//            LoginUtils.login();
            return "登录信息失效";
        } else {
            log.info("查询失败");
            return "返回：查询失败";
        }
        log.info("返回：插入成功");
        return "插入成功";
    }
}
